package algorithm

import (
	"github.com/bgmp/config"
	"github.com/bgmp/handler"
	"github.com/bgmp/middleware"
	"github.com/bgmp/model"
	"github.com/bgmp/service"
	"github.com/gin-gonic/gin"
)

func (b Base) Agent(c *gin.Context, req *AgentRequest) [][]string {
	userId := middleware.GetUserId(c)
	if req.PatientId != 0 {
		userId = req.PatientId
	}
	bgs := model.GetBgBefore(config.DB, userId, req.Time, 96)
	if len(bgs) == 0 {
		return [][]string{{"暂无药物推荐"}}
	}

	detail := &model.UserDetail{}
	detail.UserId = userId
	if err := detail.GetByUserId(config.DB); err != nil {
		handler.Errorf(c, err.Error())
		return nil
	}

	extra := transformExtra(detail)

	list, err := service.Agent(bgs, extra)
	if err != nil {
		handler.Errorf(c, err.Error())
		return nil
	}
	return list
}

func transformExtra(detail *model.UserDetail) *service.AgentExtra {
	extra := &service.AgentExtra{}

	// gender
	if detail.Gender == 1 {
		extra.Gender = 0
	} else {
		extra.Gender = 1
	}

	// age
	extra.Age = int(detail.Age)

	// bmi
	extra.Bmi = float64(detail.Weight / detail.Height / detail.Height)

	// smoke
	extra.Smoke = float64(detail.SmokingHistory)

	if detail.AlcoholDrinkingHistory == "drinker" {
		extra.Alcohol = 0
	} else {
		extra.Alcohol = 1
	}

	extra.Diabetes = float64(detail.DurationOfDiabetes)

	if detail.DiabeticMacrovascularComplications == "none" {
		extra.Macro = 0
	} else {
		extra.Macro = 1
	}

	if detail.DiabeticMicrovascularComplications == "none" {
		extra.Micro = 0
	} else {
		extra.Micro = 1
	}

	extra.Hba1c = float64(detail.Hba1c)

	extra.Hypoglycemia = int(detail.Hypoglycemia)

	return extra
}

type AgentRequest struct {
	Time      model.Time `json:"time"`
	PatientId uint       `json:"patient_id"`
}
